package com.example.aidocengine.validator;

import com.example.aidocengine.common.constant.BusinessConstant;
import com.example.aidocengine.mapper.SecondaryDeviceTerminologyMapper;
import com.example.aidocengine.pojo.entity.SecondaryDeviceTerminology;
import com.example.aidocengine.pojo.vo.TerminologyValidationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SecondaryDeviceValidator {

    @Autowired
    private SecondaryDeviceTerminologyMapper secondaryDeviceTerminologyMapper;

    // 缓存所有二次设备术语关键字，提高匹配效率
    private Set<String> terminologyKeywords;

    @PostConstruct
    public void initTerminologyCache() {
        refreshTerminologyCache();
    }

    /**
     * 刷新术语缓存
     */
    public void refreshTerminologyCache() {
        List<SecondaryDeviceTerminology> terminologies = secondaryDeviceTerminologyMapper.selectAllActive();
        terminologyKeywords = terminologies.stream()
                .map(SecondaryDeviceTerminology::getKeyword)
                .filter(StringUtils::hasText)
                .collect(Collectors.toSet());
        log.info("已加载{}个二次设备术语关键字", terminologyKeywords.size());
    }

    /**
     * 校验操作步骤是否包含二次设备术语
     */
    public TerminologyValidationVO validateSecondaryDeviceTerminology(String operationStep) {
        TerminologyValidationVO validation = new TerminologyValidationVO();
        validation.setOperationStep(operationStep);
        validation.setValidationType(BusinessConstant.VALIDATION_TYPE_SECONDARY_DEVICE);

        if (!StringUtils.hasText(operationStep)) {
            validation.setIsValid(false);
            validation.setErrorMessage("操作步骤为空");
            return validation;
        }

        // 检查是否包含二次设备术语关键字
        String matchedKeyword = findMatchedKeyword(operationStep);
        
        if (matchedKeyword != null) {
            validation.setIsValid(true);
            validation.setMatchedKeyword(matchedKeyword);
            log.debug("操作步骤匹配二次设备术语：{} -> {}", matchedKeyword, operationStep);
        } else {
            validation.setIsValid(false);
            validation.setErrorMessage(BusinessConstant.ERROR_SECONDARY_DEVICE_NOT_MATCH);
            log.debug("操作步骤未匹配任何二次设备术语：{}", operationStep);
        }

        return validation;
    }

    /**
     * 查找匹配的关键字
     */
    private String findMatchedKeyword(String operationStep) {
        if (terminologyKeywords == null || terminologyKeywords.isEmpty()) {
            refreshTerminologyCache();
        }

        String operationStepLower = operationStep.toLowerCase();

        // 优先匹配较长的关键字（更精确）
        return terminologyKeywords.stream()
                .filter(keyword -> operationStepLower.contains(keyword.toLowerCase()))
                .max((k1, k2) -> Integer.compare(k1.length(), k2.length()))
                .orElse(null);
    }

    /**
     * 检查操作步骤是否可能包含设备相关内容（用于判断是否需要进入一次设备校验）
     */
    public boolean containsDeviceReference(String operationStep) {
        if (!StringUtils.hasText(operationStep)) {
            return false;
        }

        // 检查是否包含设备相关的关键词
        String[] deviceKeywords = {
            "主变", "变压器", "母线", "线路", "开关", "刀闸", "断路器", 
            "隔离开关", "接地开关", "电容器", "电抗器", "避雷器",
            "PT", "CT", "互感器", "保护", "测控", "计量", "通信"
        };

        String operationStepLower = operationStep.toLowerCase();
        for (String keyword : deviceKeywords) {
            if (operationStepLower.contains(keyword.toLowerCase())) {
                return true;
            }
        }

        // 检查是否包含括号内容（设备双编通常在括号内）
        return operationStep.contains("（") || operationStep.contains("(");
    }
}